package milkyway.hightech.timer;

import java.util.Calendar;
import java.util.Observable;
import java.util.Timer;
import java.util.TimerTask;

/**
 *
 * @author michael
 */
public final class TimeEmitter extends Observable
{

    /**
     * constant fields to set the timespeed.
     */
    public static final long ONE_DAY = 86400000;

    /**
     * constant fields to set the timespeed.
     */
    public static final long ONE_HOUR = 3600000;

    /**
     * constant fields to set the timespeed.
     */
    public static final long ONE_MINUTE = 60000;

    /**
     * constant fields to set the timespeed.
     */
    public static final long ONE_MONTH = 0x9a7ec800L;

    /**
     * constant fields to set the timespeed.
     */
    public static final long ONE_SECOND = 1000;

    /**
     * constant fields to set the timespeed.
     */
    public static final long ONE_YEAR = 0x757b12c00L;

    /**
     * period of time in which time will be updated.
     */
    public static final int TICK_FREQUENCE = 1000;

    /**
     *
     */
    private static TimeEmitter timeEmitter;

    /**
     * set the default timespeed.
     */
    private long timeSpeed = ONE_SECOND;

    /**
     *
     */
    private Calendar calendar = Calendar.getInstance();

    /**
     * the frame containing the clock.
     */
    private Clock clock;

    /**
     *
     */
    private Timer timer;

    /**
     * creates the clock to display time.
     */
    private TimeEmitter()
    {
        clock = new Clock(calendar);
    }

    /**
     * returns the instance of this TimeEmitter.
     * @return this TimeEmitter
     */
    public static TimeEmitter getInstance()
    {
        if (timeEmitter == null)
        {
            timeEmitter = new TimeEmitter();
        }

        return timeEmitter;
    }

    /**
     * returns a new calendarobject.
     * @return a clone of this calendar object
     */
    public Calendar getCalendar()
    {
        return (Calendar)calendar.clone();
    }

    /**
     * increases the timespeed.
     * @param value to set the timespeed
     */
    public void setTimeSpeed(final long value)
    {
        this.timeSpeed = value;
    }

    /**
     * let time run and redraws the clock.
     */
    public void startTiming()
    {
        if (timer == null)
        {
            timer = new Timer();
            timer.scheduleAtFixedRate(new TimerTask()
                {
                    @Override
                    public void run()
                    {
                        setChanged();
                        calendar.setTimeInMillis(calendar.getTimeInMillis()
                            + timeSpeed);
                        
                        clock.repaint();
                        notifyObservers(this);
                    }
                }, TICK_FREQUENCE, TICK_FREQUENCE);
        }
    }
}